package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import model.Piece;
import model.Player;
import model.Sequence;
import view.EditorPanel;
import view.GUI;
import view.InstrumentButton;
import view.TrackPanel;
import view.tool.SequenceTool;

/**
 * Listens for events that want to add a new sequence to the piece.
 */
public class AddSequenceListener implements ActionListener {

	private Piece piece;
	private Player player;
	private GUI gui;

	public AddSequenceListener(Player player, GUI gui) {
		this.piece = player.getPiece();
		this.player = player;
		this.gui = gui;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		//Create a new blank sequence and add it to the piece.
		Sequence sequence = new Sequence(piece.getLength());
		piece.addSequence(sequence);

		//Set up a TrackPanel and InstrumentButton to add to the GUI
		TrackPanel trackPanel = new TrackPanel(sequence.getAllNotes());
		trackPanel.setTrackChangeListener(new TrackModifiedListener(player, sequence));

		SequenceTool sequenceTool = new SequenceTool(sequence.getVolume());
		sequenceTool.addSequenceChangeListener(
			new SequenceChangeListener(piece, sequence, gui)
		);

		InstrumentButton instrumentButton = new InstrumentButton(
			sequence.getInstrument(), sequenceTool
		);

		EditorPanel editorPanel = gui.getEditorPanel();
		editorPanel.addSequence(instrumentButton, trackPanel);

		//Revalidate the panel to maintain correct sizing and position
		editorPanel.revalidate();
		//Scroll down to keep new sequence button in view.
		editorPanel.scrollToBottom();
	}



}
